package com.test45_JUC;

import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * 并发单值集合
 */
public class Demo17_CopyOnWriteArrayList {

    public static void main(String[] args) {
        // test1();
        test2();
    }

    /**
     * CopyOnWriteArrayList
     * 不会像Collections那样变为同步集合
     * 可以直接进行异步集合的处理操作
     */
    public static void test1() {
        List<String> list = new CopyOnWriteArrayList<>();
        for (int x = 0; x < 10; x++) {
            new Thread(() -> {
                for (int y = 0; y < 10; y++) {
                    list.add("【" + Thread.currentThread().getName() + "】www.yootk.com");
                    System.out.println(list);
                }
            }, "集合操作线程-"+x).start();
        }
    }

    /**
     * CopyOnWriteArraySet
     * 内部是使用CopyOnWriteArrayList实现的
     */
    public static void test2() {
        Set<String> set = new CopyOnWriteArraySet<>();
        for (int x = 0; x < 10; x++) {
            new Thread(() -> {
                for (int y = 0; y < 10; y++) {
                    set.add("【" + Thread.currentThread().getName() + "】www.yootk.com");
                    System.out.println(set);
                }
            }, "集合操作线程-"+x).start();
        }
    }
}
